#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "pthread.h"

#define BUFFER_SIZE 16

/* 设置一个缓冲区（结构体） */
struct prodcons {
int buffer[BUFFER_SIZE];  /* 缓冲区数组 */
pthread_mutex_t lock; /* 互斥锁 */
int readpos, writepos;/* 读写的位置 */
pthread_cond_t notempty;  /* 缓冲区非空信号 */
pthread_cond_t notfull;   /* 缓冲区非满信号 */
};

/* Initialize a buffer */
void init(struct prodcons * b)
{
pthread_mutex_init(&b->lock, NULL);
pthread_cond_init(&b->notempty, NULL);
pthread_cond_init(&b->notfull, NULL);
 b->readpos = 0;
b->writepos = 0;
}
/*--------------------------------------------------------*/
/* Store an integer in the buffer */
void put(struct prodcons * b, int data)
{
    pthread_mutex_lock(&b->lock);

    /*等待缓冲区非满的时候，才可以向其中写入数据 */
    while ((b->writepos + 1) % BUFFER_SIZE == b->readpos) {
        printf("wait for not full\n");
pthread_cond_wait(&b->notfull, &b->lock);
}
 /* 写过数据之后，将指针向前移动一位 */
    b->buffer[b->writepos] = data;
    b->writepos++;
    if (b->writepos >= BUFFER_SIZE) b->writepos = 0;
/* 设置非空信号 */
    pthread_cond_signal(&b->notempty);

    pthread_mutex_unlock(&b->lock);
}

/* 其实读和写的代码基本上差不多，只不过最后要把非空设置为非满 */
int get(struct prodcons * b)
{
int data;
pthread_mutex_lock(&b->lock);

/* Wait until buffer is not empty */
while (b->writepos == b->readpos) {
printf("wait for not empty\n");
    pthread_cond_wait(&b->notempty, &b->lock);
}
/* Read the data and advance read pointer */
data = b->buffer[b->readpos];
b->readpos++;
if (b->readpos >= BUFFER_SIZE) b->readpos = 0;
/* Signal that the buffer is now not full */
pthread_cond_signal(&b->notfull);//设置状态信号量，这个是为了“我们”（操作系统）方便地“看出来”这个单元到底可不可用

pthread_mutex_unlock(&b->lock);//释放互斥锁。这一步是很重要的，因为某一个单元在同一时刻只能被一个消费者/生产者使用（不可能同时写数据或者读数据，甚至也不可能同时有两个“人”读或者写数据）
return data;
}
/*--------------------------------------------------------*/
#define OVER (-1)
struct prodcons buffer;
/*下面的函数是生产者和消费者的主要的调用函数（调用上面的函数）*/
void * producer(void * data)
{
    int n;
    for (n = 0; n < 1000; n++) {
    printf(" put-->%d\n", n);
    put(&buffer, n);
    }
put(&buffer, OVER);
printf("producer stopped!\n");
return NULL;
}       
    /*--------------------------------------------------------*/
void * consumer(void * data)
{
  int d;
while (1) {
d = get(&buffer);
if (d == OVER ) break;
printf("  %d-->get\n", d);
}
printf("consumer stopped!\n");
return NULL;
}
/*主函数：可以注意到先有生产者再有消费者*/
int main(void)
{
    pthread_t th_a, th_b;
    void * retval;

init(&buffer);
pthread_create(&th_a, NULL, producer, 0);
pthread_create(&th_b, NULL, consumer, 0);
/* Wait until producer and consumer finish. */
pthread_join(th_a, &retval);
pthread_join(th_b, &retval);

return 0;
}
